const fs = require('fs')
const path = require('path')

exports.import =  (config) => {
    let hook_path = config.default_operator_hook_path = config.default_operator_hook_path || 'service/auto'

    let hook_dir = path.join(process.cwd(), hook_path)
    let hooks = {}

    if (fs.existsSync(hook_dir)) {
        let files = fs.readdirSync(hook_dir)
        for (let i = 0; i < files.length; i++) {
            if (fs.statSync(path.join(hook_dir, files[i])).isFile() && files[i] === 'index.js') {
                hooks = require(path.join(hook_dir, files[i])) //global
            } else if (fs.statSync(path.join(hook_dir, files[i])).isDirectory()) {
                // 数据库连接下的模型
                let conn_dirs = fs.readdirSync(path.join(hook_dir, files[i]))

                hooks[files[i]] = {}
                for (let ci = 0; ci < conn_dirs.length; ci++) {
                    if (fs.statSync(path.join(hook_dir, files[i], conn_dirs[ci])).isFile() && conn_dirs[ci] === 'index.js') {
                        hooks[files[i]] = require(path.join(hook_dir, files[i], conn_dirs[ci])) // conn
                    } else if (fs.statSync(path.join(hook_dir, files[i], conn_dirs[ci])).isDirectory()) {
                        hooks[files[i]][conn_dirs[ci]] = {}
                        fs.readdirSync(path.join(hook_dir, files[i], conn_dirs[ci])).filter((file) => {return (path.extname(file) === '.js')}).forEach(f => {
                            let name = path.basename(f, path.extname(f))
                            hooks[files[i]][conn_dirs[ci]][name] = require(path.join(hook_dir, files[i], conn_dirs[ci], f))
                        })
                    }
                }
            }
        }
    }

    return hooks
}
